package org.jboss.seam.example.registration;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Identity;

//@Stateless
@Name("authenticator")
public class AuthenticatorImpl //implements Authenticator 
{


	@In("userDatabase")	
	private EntityManager entityManager;
	
	@Out(value = "current_user", required = false)
	private User user;
	
	@Logger Log log;

	public boolean authenticate() {
		// 以下代码无效！在已经登录的状态下，不会再调用authenticate()方法。
		/*if (Identity.instance().isLoggedIn()) {
			FacesMessages.instance().add("You are aready logged in! There is no need to login duplicately for you.");
			return false;
		}*/
		try {
			user = (User) entityManager
					.createQuery(
							"from User where username = :username and password = :password")
					.setParameter("username", Identity.instance().getUsername())
					.setParameter("password", Identity.instance().getPassword())
					.getSingleResult();
			if (user.getRoles() != null && !user.getRoles().isEmpty()) {
				for (Role role : user.getRoles())
					Identity.instance().addRole(role.name());
			}
			return true;
		} catch (NoResultException ex) {
			log.info("Authentication failed with username: #{identity.username}");
			return false;
		}
	}

}
